<?php

namespace app\controllers;

use app\models\User;
use app\models\Good;
use app\models\UserCollect;
use app\tools\Re;
use Yii;

class UserCollectController extends BaseController
{
    public function actionCollectList(){
      $openid = Yii::$app->request->post('openid', '');
      $user_info = User::find()->where(['openid' => $openid, 'status' => 1])->one();
      if (!$user_info) {
        return Re::data(null, '用户信息读取错误', Re::ERROR);
      }
      $user_collect_list = UserCollect::find()->where(['user_id' => $user_info->id, 'is_collect' => 1])->orderBy("created_at desc")->all();
      $user_collect_data = [];
      if ($user_collect_list) {
        foreach ($user_collect_list as $v) {
          $user_collect_data[] = [
            'id' => $v->id,
            'good_id' => $v->good_id,
            'good_name' => $v->good->name,
            'good_img' => $v->good->img,
            'good_price' => $v->good->price,
            'created_time' => date('Y-m-d H:i:s', $v->created_at),
          ];
        }
      }
      return Re::data(['data' => $user_collect_data]);
    }

    public function actionCollectGood() {
      $good_id = Yii::$app->request->post('good_id', 0);
      $openid = Yii::$app->request->post('openid', '');
      $good_info = Good::find()->where(['id' => $good_id, 'status' => 1])->one();
      if (!$good_info) {
        return Re::data(null, '商品信息不存在', Re::ERROR);
      }
      
      $user_info = User::find()->where(['openid' => $openid, 'status' => 1])->one();
      if (!$user_info) {
        return Re::data(null, '用户信息读取错误', Re::ERROR);
      }
      $user_collect = UserCollect::find()->where(['user_id' => $user_info->id, 'good_id' => $good_id])->one();
      if (!$user_collect) {
        $user_collect = new UserCollect();
        $user_collect->user_id = $user_info->id;
        $user_collect->good_id = $good_id;
        $user_collect->is_collect = 1;
      } else {
        $user_collect->is_collect = $user_collect->is_collect == 0 ? 1 : 0;
      }
      $user_collect->created_at = time();
      if (!$user_collect->save()) {
        return Re::data(null, '操作失败', Re::ERROR);
      }
      return Re::data();
    }
}
